import 'dart:convert';
import 'dart:typed_data';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/models/remote_control_received_model.dart';
import 'package:flutter_oldman_health/utils/event_bus.dart';
import 'package:flutter_oldman_health/utils/remote_control_utils.dart';
import 'package:flutter_oldman_health/widget/listener_container.dart';

//远程操控
class FamilyRemoteControlPage extends StatefulWidget {
  int pos = 0;
  String familyId;
  bool active = true;

  FamilyRemoteControlPage({Key k, this.familyId, this.active}) : super(key: k);

  @override
  State<StatefulWidget> createState() => FamilyRemoteControlState();
}

class FamilyRemoteControlState extends State<FamilyRemoteControlPage> {
  // 收到老人机截图
  bool showCaptureScreen = false;

  //是否已经断开连接
  bool hasDisconnect = false;
  bool stopAudio = false;
  AudioCache audioCache;
  AudioPlayer audioPlayer;
  Uint8List bytes;
  Size screenSize;
  int screenTime = 0;

  @override
  void initState() {
    super.initState();
    audioCache = AudioCache();
    audioPlayer = AudioPlayer();

    RemoteControlTool().connect(null);
    RemoteControlTool().subscribeFamilyTopic(widget.familyId, widget.active);
    if (!widget.active) {
      playSounds();
    }
    setEventBus();
  }

  void playSounds() {
    audioCache.fixedPlayer = audioPlayer; //核心
    //播放用audioCache
    // audioCache.play('sounds/sirius.ogg', volume: 2.0); //volume默认1.0代表音量
    audioCache.loop('sounds/Helium.wav', volume: 2.0); //volume默认1.0代表音量
    //暂停用audioPlayer
    // audioPlayer.pause();
  }

  void stopSounds() {
    if (audioPlayer != null && !stopAudio) {
      audioPlayer.stop().then((value) {
        stopAudio = value == 1;
      });
    }
  }

  @override
  void dispose() {
    print('dispose');
    // _disconnect();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return Scaffold(
        body: WillPopScope(
            onWillPop: () async {
              print('WillPopScope myselfCancel');
              _disconnect();
              Navigator.pop(context, 1);
              return true;
            },
            child: Container(
                width: screenSize.width,
                padding: EdgeInsets.only(top: 16),
                color: showCaptureScreen ? Colors.white30 : Colors.black,
                child: Stack(children: [_getMainLayout()]))));
  }

  void setEventBus() {
    //CaptureScreenFinished 收到截图
    EventBus().on(Constant.REMOTE_CONTROL_CAPTURE_SCREEN, (pt) {
      RemoteCaptureScreenModel screenModel =
          RemoteCaptureScreenModel.fromJson(json.decode(pt));
      screenTime = int.parse(screenModel.msgId);
      if (screenModel.success()) {
        setState(() {
          showCaptureScreen = true;
          bytes = Base64Decoder().convert(screenModel.imageBase64);
        });
      } else {
        EasyLoading.showInfo("获取对方屏幕失败");
        print('获取对方屏幕失败 myselfCancel');
        // _disconnect();
        // Navigator.pop(context, 1);
        //https://www.javaroad.cn/static/images/avatar.png
      }
    });
    EventBus().on("delayed_request_control", (p) {
      if (!showCaptureScreen) {
        EasyLoading.showInfo("对方未接听或者不在线");
        _disconnect();
        Navigator.pop(context, 1);
      }
    });

    EventBus().on("_disconnect", (p0) {
      _disconnect();
      Navigator.pop(context, 1);
    });
  }

  //  断开连接
  _disconnect() {
    if (!hasDisconnect) {
      hasDisconnect = true;
      RemoteControlTool().disFamilyConnect();
      EventBus().off("delayed_request_control");
      EventBus().off("_disconnect");
      EventBus().off(Constant.REMOTE_CONTROL_CAPTURE_SCREEN);
      //停止播放
      stopSounds();
    }
  }

  Widget _getWaitingLayout() {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Text((widget.active ? "等待对方接听中......" : "对方申请被控制......"),
          style: TextStyle(color: Colors.white)),
      Padding(padding: EdgeInsets.all(16)),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
        if (!widget.active) _getElevatedButtonLayout(false),
        _getElevatedButtonLayout(true)
      ])
    ]);
  }

  Widget _getElevatedButtonLayout(bool isCancel) {
    return ElevatedButton(
        onPressed: () {
          if (!isCancel) {
            stopSounds();
            RemoteControlTool().agreeRemoteControl();
          } else {
            if (!widget.active) {
              stopSounds();
              RemoteControlTool().disAgreeRemoteControl();
            } else {
              RemoteControlTool().cancelRemoteControl();
            }
            print('_getElevatedButtonLayout myselfCancel');
            Navigator.pop(context, 1);
            _disconnect();
          }
        },
        style: ButtonStyle(
            textStyle: MaterialStateProperty.all(TextStyle(fontSize: 18)),
            //字体颜色
            foregroundColor: MaterialStateProperty.all(Colors.white),
            //背景颜色
            backgroundColor: MaterialStateProperty.all(
                !isCancel ? Colors.greenAccent : Colors.red),
            shape: MaterialStateProperty.all(CircleBorder(
              side: BorderSide(
                  color: !isCancel ? Colors.greenAccent : Colors.red),
            ))),
        child: Padding(
            padding: EdgeInsets.all(22), child: Text(!isCancel ? "同意" : "取消")));
  }

  Widget _showCaptureScreen() {
    return Container(
      width: screenSize.width,
      height: screenSize.height,
      child: //Stack(children: [
          ListenerContainer(
              size: screenSize,
              child: Container(
                  child: Image.memory(bytes,
                      gaplessPlayback: true,
                      width: screenSize.width,
                      height: screenSize.height,
                      fit: BoxFit.fill))),
      // CommonContainer(
      //     GestureDetector(
      //         onTap: () {
      //           _disconnect();
      //           Navigator.pop(context,1);
      //         },
      //         child: Text("断开连接",
      //             style: TextStyle(color: Colors.red, fontSize: 18))),
      //     margin: EdgeInsets.only(top: 45, left: 4),
      //     padding: EdgeInsets.fromLTRB(18, 8, 18, 8),
      //     colorBg: Color(0x00666666))  ])
    );
  }

  Widget _getMainLayout() {
    return showCaptureScreen ? _showCaptureScreen() : _getWaitingLayout();
  }

  Widget _getBackButton() {
    return Positioned(
        left: 28,
        top: 38,
        child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              _disconnect();
              Navigator.pop(context, 1);
            },
            child: Icon(Icons.arrow_back_ios, color: Colors.white)));
  }
}
